import 'package:byw_blog/utils/ParameterUtil.dart';
import 'package:sqflite/sqflite.dart';
import 'package:path/path.dart';

class DatabaseHelp {
  static Database? database;

  static Future<void> initDb() async {
    String databasesPath = await getDatabasesPath();
    String path = join(databasesPath, ParameterUtil.DATABASE_NAME);
    database = await openDatabase(
      path,
      version: ParameterUtil.DATABASE_VERSION,
      onCreate: (Database db, int version) async {
        //路径下没有数据库文件时创建数据库的回调
      },
      onUpgrade: (Database db, int oldVersion, int newVersion) async {
        // 数据库升级回调
      },
      onOpen: (Database db) async {
        // 打开数据库的回调
      },
    );
    // 创建表person
    database?.execute(
        'CREATE TABLE IF NOT EXISTS ${ParameterUtil.TABLE_SEARCH_HISTORY}('
        'id INTEGER PRIMARY KEY AUTOINCREMENT,'
        ' value TEXT,'
        ' time TEXT)');
  }

  static Database getDatabase() {
    if (database == null) {
      initDb();
    }
    return database!;
  }

  Future<int> insert(String table, Map<String, Object?> values,
      {String? nullColumnHack, ConflictAlgorithm? conflictAlgorithm}) {
    return database!.insert(table, values,
        nullColumnHack: nullColumnHack, conflictAlgorithm: conflictAlgorithm);
  }

  Future<List<Map<String, Object?>>> query(String table,
      {bool? distinct,
      List<String>? columns,
      String? where,
      List<Object?>? whereArgs,
      String? groupBy,
      String? having,
      String? orderBy,
      int? limit,
      int? offset}) {
    return database!.query(table,
        distinct: distinct,
        columns: columns,
        where: where,
        whereArgs: whereArgs,
        groupBy: groupBy,
        having: having,
        orderBy: orderBy,
        limit: limit,
        offset: offset);
  }

  Future<int> update(String table, Map<String, Object?> values,
      {String? where,
      List<Object?>? whereArgs,
      ConflictAlgorithm? conflictAlgorithm}) {
    return database!.update(table, values,
        where: where,
        whereArgs: whereArgs,
        conflictAlgorithm: conflictAlgorithm);
  }

  Future<int> delete(String table, {String? where, List<Object?>? whereArgs}) {
    return database!.delete(table, where: where, whereArgs: whereArgs);
  }
}
